package board;

import java.util.*;
import java.awt.Toolkit;

import board.command.Command;

/**
 * Allows moves to be played on the Board and taken back. 
 * @author TKington
 *
 */
public class UndoController
{
	/** The stack that holds Commands that can be undone. */
    private LinkedList<Command> undoStack;

    /** Creates new UndoController */
    public UndoController()
    {
        undoStack = new LinkedList<Command>();
    }

    /**
     * Clears the command history.
     *
     */
    public void clear()
    {
        undoStack.clear();
    }

    /**
     * Executes a Command.
     * @param cmd the Command
     * @param b the Board to perform the Command on
     * @return true if the Command was successful
     */
    public boolean doCommand(Command cmd, Board b)
    {
        //  Execute command
        boolean success = cmd.doIt(b);

        //  If successful, it can be undone
        if(success)
            undoStack.addFirst(cmd);
        return success;
    }

    /**
     * Undoes the last Command.
     * @param b the Board to operate on
     */
    public void undo(Board b)
    {
        int size = undoStack.size();

        //  If there's something to undo, undo it
        if(size > 0)
        {
            Command c = undoStack.removeFirst();
            c.undoIt(b);
        }
        else Toolkit.getDefaultToolkit().beep();
    }
}
